﻿using ManagoMes.Read.API.Applications.SellStockSearchRead;
using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.QRUPC;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace ManagoMes.Read.API.Applications.QRUPCSearch
{
    public class QUCodeSearchHandler : IRequestHandler<QUCodeSearchCommand, CodePageDTO<QRUPCDTO>>
    {
        private readonly IBateRepository<QRUPCDTO> _QUCodeRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="qUCodeRepository"></param>
        public QUCodeSearchHandler(IBateRepository<QRUPCDTO> qUCodeRepository)
        {
            _QUCodeRepository = qUCodeRepository;
        }
        /// <summary>
        /// 赋码管理列表查询+分页
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<CodePageDTO<QRUPCDTO>> Handle(QUCodeSearchCommand request, CancellationToken cancellationToken)
        {
            //连接数据库
            DapperHelper dapper = new DapperHelper();
            string conn = dapper.MangoMesRead;
            //分页查询
            CodePageDTO<QRUPCDTO> str = new CodePageDTO<QRUPCDTO>();
            var pageNum = (request.pageIndex - 1) * request.pageSize;
            //实体DTO
            QRUPCDTO ssk = new QRUPCDTO();
            string sql = "select * from qucode";
            var result = _QUCodeRepository.GetAll(sql, ssk, conn).ToList();
            if (request.QUCodeType > -1)
            {
                result = result.Where(p => p.QUCodeType == Convert.ToString(request.QUCodeType)).ToList();
            }
            if (request.QUCodeStart > -1)
            {
                result = result.Where(p => p.QUCodeStart == Convert.ToString(request.QUCodeStart)).ToList();
            }
            str.TotalCount = result.Count();
            str.PageCount = (int)Math.Ceiling((result.Count() * 1.0) / request.pageSize);
            result = result.OrderBy(p => p.QUCodeId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            str.Data = result;
            foreach (var item in str.Data)
            {
                item.QUCodeFormat = item.QUCodeFormat == "0" ? "QR二维码" : "UPC条形码";
                item.QUCodeType = item.QUCodeType == "0" ? "物料条码" :(item.QUCodeType == "1" ? "库存条码" : "仓库条码");
                item.QUCodeStart = item.QUCodeStart == "0" ? "生效" : "失效";
            }
            str.Code = 0; 
            return str;
        }
    }
}
